package com.ifacebox.web.admin.controller;

import com.ifacebox.web.admin.os.manager.OsMonitorManager;
import com.ifacebox.web.common.annotation.UserAgentRequest;
import com.ifacebox.web.common.model.UserAgent;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author znn
 */
public class BaseViewController extends BaseController {
    protected static final String ATTR_PLATFORM_PROPERTIES = "platformProperties";
    protected static final String ATTR_SYSTEM_PROPERTY = "systemProperty";
    protected static final String ATTR_SERVER_STATUS = "status";
    protected static final String ATTR_SERVER_ERROR = "error";
    protected static final String ATTR_ERROR_MESSAGE = "message";
    protected static final String ATTR_ERROR_TRACE = "trace";

    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute(ATTR_PLATFORM_PROPERTIES, platformManager.getPlatformProperties());
        model.addAttribute(ATTR_SYSTEM_PROPERTY, OsMonitorManager.getSystemProperty());
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView error(@UserAgentRequest UserAgent userAgent, Exception e) {
        traceLoggerService.addTraceLogger(userAgent, e.toString());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject(ATTR_SERVER_STATUS, HttpStatus.INTERNAL_SERVER_ERROR.value());
        modelAndView.addObject(ATTR_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        modelAndView.addObject(ATTR_ERROR_MESSAGE, e.getMessage());
        modelAndView.addObject(ATTR_ERROR_TRACE, new StringWriter() {
            {
                e.printStackTrace(new PrintWriter(this));
            }
        }.toString());
        modelAndView.setViewName(VIEWS_ADMIN_ERROR);
        return modelAndView;
    }
}
